/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pt.moltos.rabbit;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import pt.moltos.chatmessaging.Chatwindow;
import static pt.moltos.rabbit.RabbitController.EXCHANGE_NAME;

/**
 *
 * @author MoLt1eS
 */
public class Receive extends Thread{
    
    private Chatwindow window;

    public Receive() {
    }

    public Receive(Chatwindow window) {
        this.window = window;
    }
    
    
    @Override
    public void run(){
        try {
            ConnectionFactory factory = new ConnectionFactory();
            
            factory.setHost(RabbitController.SERVER_IP);
            factory.setUsername(RabbitController.USERNAME);
            factory.setPassword(RabbitController.PASSWORD);
            
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, EXCHANGE_NAME, "");
            
            
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
            
            QueueingConsumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
            
            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                String message = new String(delivery.getBody());
                if(window!= null){
                    window.addText(" [x] Received '" + message + "'\n");
                }
                else{
                    System.out.println(" [x] Received '" + message + "'");
                }
            }   
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (ShutdownSignalException ex) {
            ex.printStackTrace();
        } catch (ConsumerCancelledException ex) {
            ex.printStackTrace();
        }
    }
}
